<template>
  <div class="register-box">
    <div p-5>
      <div class="register-box-top">
        <div class="register-box-top-tittle">{{ boxTittle }}</div>
      </div>
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :labelWrap="true"
      >
        <div class="register-box-info">
          <div class="registerBox-tittle">
            <div class="registerBox-tittle-left"></div>
            <div class="registerBox-tittle-right">案件信息</div>
          </div>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="8">
              <a-form-item
                label="案件来源"
                name="sourceId"
                :labelCol="{ style: { width: '82px' } }"
              >
                <a-select
                  v-model:value="formState.sourceId"
                  placeholder="请选择案件来源"
                  :options="sourceTypeOptions"
                  allowClear
                >
                </a-select> </a-form-item
            ></a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item
                label="其他来源"
                name="otherSource"
                :labelCol="{ style: { width: '82px' } }"
                v-if="
                  sourceTypeOptions?.filter((item) => item.value == formState.sourceId)[0]?.label ==
                  '其他'
                "
              >
                <a-input
                  v-model:value="formState.otherSource"
                  placeholder="请填写其他来源"
                  autocomplete="off"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="8">
              <a-form-item
                label="案由"
                name="caseActionId"
                :labelCol="{ style: { width: '82px' } }"
              >
                <a-input-group compact>
                  <a-input
                    :value="formState.caseActionName"
                    style="width: calc(100% - 88px)"
                    placeholder="请选择案由"
                  />
                  <a-button type="primary" @click="showModal" ghost>案由选择</a-button>
                </a-input-group>
              </a-form-item>
              <a-modal v-model:open="open" title="案由选择" :width="1000" @ok="handleOk">
                <DynamicTable
                  :row-key="(record) => record.id"
                  :row-selection="{
                    selectedRowKeys: selectedRowKeys,
                    onChange: onRowChange,
                    type: 'radio',
                  }"
                  :columns="columns"
                  :data-request="loadData"
                  size="small"
                  bordered
                  :showIndex="true"
                  :showToolBar="false"
                  :autoHeight="true"
                />
              </a-modal>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item
                label="
            执法方式"
                name="enforceWay"
                :labelCol="{ style: { width: '82px' } }"
              >
                <a-select
                  v-model:value="formState.enforceWay"
                  placeholder="请选择执法方式"
                  :options="enforceWayOptions"
                  allowClear
                >
                </a-select>
              </a-form-item> </a-col
          ></a-row>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="16">
              <a-form-item
                label="
            简要案情"
                name="caseBrief"
                :labelCol="{ style: { width: '82px' } }"
              >
                <a-textarea
                  v-model:value="formState.caseBrief"
                  placeholder="请输入简要案情"
                  :maxlength="128"
                  :rows="4"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                  show-count
                ></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="base-info">
          <div class="registerBox-tittle casePadding">
            <div class="registerBox-tittle-left"></div>
            <div class="registerBox-tittle-right">基本信息</div>
          </div>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="12">
              <a-form-item
                label="当事人类型"
                name="partyType"
                class="partyType"
                :labelCol="{ style: { width: '95px' } }"
              >
                <a-radio-group
                  v-model:value="formState.partyType"
                  option-type="button"
                  button-style="solid"
                  @change="changeParty"
                >
                  <a-radio :value="0">自然人</a-radio>
                  <a-radio :value="1">法人</a-radio>
                  <a-radio :value="2">个体工商户</a-radio>
                  <a-radio :value="3">非法人组织</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="baseBox">
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 0">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="姓名" name="placeName">
                  <a-input
                    v-model:value="formState.placeName"
                    placeholder="请输入姓名"
                    autocomplete="off"
                    show-count
                    :maxlength="16"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="性别" name="sex">
                  <a-select
                    v-model:value="formState.sex"
                    placeholder="请选择性别"
                    :options="sexOptions"
                    allowClear
                  >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="出生日期" name="birthDate">
                  <a-date-picker
                    style="width: 100%"
                    v-model:value="formState.birthDate"
                    placeholder="请选择出生日期"
                    :valueFormat="'YYYY-MM-DD'"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="联系电话" name="contactsTel">
                  <a-input
                    v-model:value="formState.contactsTel"
                    placeholder="请输入联系电话"
                    autocomplete="off"
                    show-count
                    :maxlength="13"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="证件类型" name="idType">
                  <a-select
                    v-model:value="formState.idType"
                    placeholder="请选择证件类型"
                    :options="idTypeOptions"
                    allowClear
                  >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="证件号码" name="idCode">
                  <a-input
                    v-model:value="formState.idCode"
                    placeholder="请输入证件号码"
                    autocomplete="off"
                    show-count
                    :maxlength="caseIdcode(formState.idType)"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="住址" name="operateArea">
                  <a-cascader
                    v-model:value="formState.operateArea"
                    :options="addressOptions"
                    placeholder="请选择住址"
                    :fieldNames="areaFieldNames"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input
                    v-model:value="formState.operateAddress"
                    placeholder="请输入详细地址"
                    autocomplete="off"
                    show-count
                    :maxlength="68"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 1">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位名称" name="placeName">
                  <a-auto-complete
                    v-model:value="formState.placeName"
                    placeholder="请输入单位名称"
                    :options="placeOptions"
                    @select="onSelect"
                    @blur="changeInfo"
                    show-count
                    :maxlength="16"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位联系电话" name="contactsTel">
                  <a-input
                    v-model:value="formState.contactsTel"
                    placeholder="请输入单位联系电话"
                    autocomplete="off"
                    show-count
                    :maxlength="13"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="注册地址" name="registerArea">
                  <a-cascader
                    v-model:value="formState.registerArea"
                    :options="addressOptions"
                    placeholder="请选择注册地址"
                    :fieldNames="areaFieldNames"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="registerAddress">
                  <a-input
                    v-model:value="formState.registerAddress"
                    placeholder="请输入详细注册地址"
                    autocomplete="off"
                    show-count
                    :maxlength="68"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营地址" name="operateArea">
                  <a-cascader
                    v-model:value="formState.operateArea"
                    :options="addressOptions"
                    placeholder="请选择经营地址"
                    :fieldNames="areaFieldNames"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input
                    v-model:value="formState.operateAddress"
                    placeholder="请输入详细经营地址"
                    autocomplete="off"
                    show-count
                    :maxlength="68"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="法人" name="headName">
                  <a-input
                    v-model:value="formState.headName"
                    placeholder="请输入法人姓名"
                    autocomplete="off"
                    show-count
                    :maxlength="16"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="法人电话" name="headTel">
                  <a-input
                    v-model:value="formState.headTel"
                    placeholder="请输入法人电话"
                    autocomplete="off"
                    show-count
                    :maxlength="13"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="社会统一信用代码" name="idCode" class="itemForm">
                  <a-input
                    v-model:value="formState.idCode"
                    placeholder="请输入社会统一信用代码"
                    autocomplete="off"
                    show-count
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 2">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="字号名称" name="placeName">
                  <a-input
                    v-model:value="formState.placeName"
                    placeholder="请输入字号名称"
                    autocomplete="off"
                    show-count
                    :maxlength="15"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营者姓名" name="headName">
                  <a-input
                    v-model:value="formState.headName"
                    placeholder="请输入经营者姓名"
                    autocomplete="off"
                    show-count
                    :maxlength="16"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="注册地址" name="registerArea">
                  <a-cascader
                    v-model:value="formState.registerArea"
                    :options="addressOptions"
                    placeholder="请选择注册地址"
                    :fieldNames="areaFieldNames"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="registerAddress">
                  <a-input
                    v-model:value="formState.registerAddress"
                    placeholder="请输入详细注册地址"
                    autocomplete="off"
                    show-count
                    :maxlength="68"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营地址" name="operateArea">
                  <a-cascader
                    v-model:value="formState.operateArea"
                    :options="addressOptions"
                    placeholder="请选择经营地址"
                    :fieldNames="areaFieldNames"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input
                    v-model:value="formState.operateAddress"
                    placeholder="请输入详细经营地址"
                    autocomplete="off"
                    show-count
                    :maxlength="68"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位联系电话" name="contactsTel">
                  <a-input
                    v-model:value="formState.contactsTel"
                    placeholder="请输入单位联系电话"
                    autocomplete="off"
                    show-count
                    :maxlength="13"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="社会统一信用代码" name="idCode" class="itemForm">
                  <a-input
                    v-model:value="formState.idCode"
                    placeholder="请输入社会统一信用代码"
                    autocomplete="off"
                    show-count
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 3">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位名称" name="placeName">
                  <a-auto-complete
                    v-model:value="formState.placeName"
                    placeholder="请输入单位名称"
                    :options="placeOptions"
                    @select="onSelect"
                    @blur="changeInfo"
                    show-count
                    :maxlength="16"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位联系电话" name="contactsTel">
                  <a-input
                    v-model:value="formState.contactsTel"
                    placeholder="请输入单位联系电话"
                    autocomplete="off"
                    show-count
                    :maxlength="13"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="注册地址" name="registerArea">
                  <a-cascader
                    v-model:value="formState.registerArea"
                    :options="addressOptions"
                    placeholder="请选择注册地址"
                    :fieldNames="areaFieldNames"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="registerAddress">
                  <a-input
                    v-model:value="formState.registerAddress"
                    placeholder="请输入详细注册地址"
                    autocomplete="off"
                    show-count
                    :maxlength="68"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营地址" name="operateArea">
                  <a-cascader
                    v-model:value="formState.operateArea"
                    :options="addressOptions"
                    placeholder="请选择经营地址"
                    :fieldNames="areaFieldNames"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input
                    v-model:value="formState.operateAddress"
                    placeholder="请输入详细经营地址"
                    autocomplete="off"
                    show-count
                    :maxlength="68"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="负责人" name="headName">
                  <a-input
                    v-model:value="formState.headName"
                    placeholder="请输入负责人姓名"
                    autocomplete="off"
                    show-count
                    :maxlength="16"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="负责人电话" name="headTel">
                  <a-input
                    v-model:value="formState.headTel"
                    placeholder="请输入负责人电话"
                    autocomplete="off"
                    show-count
                    :maxlength="13"
                  />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="社会统一信用代码" name="idCode" class="itemForm">
                  <a-input
                    v-model:value="formState.idCode"
                    placeholder="请输入社会统一信用代码"
                    autocomplete="off"
                    show-count
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="register-info">
          <div class="registerBox-tittle">
            <div class="registerBox-tittle-left"></div>
            <div class="registerBox-tittle-right">立案信息</div>
          </div>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="8">
              <a-form-item
                label="立案意见"
                name="opinionId"
                :labelCol="{ style: { width: '82px' } }"
              >
                <a-select
                  v-model:value="formState.opinionId"
                  placeholder="请选择立案意见"
                  :options="opinionOptions"
                  allowClear
                >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item
                :label="
                  caseSenNameLabel(
                    opinionOptions?.filter((item) => item.value == formState.opinionId)[0]?.label,
                  )
                "
                name="sendName"
                v-if="
                  opinionOptions?.filter((item) => item.value == formState.opinionId)[0]?.label ==
                    '其他' ||
                  opinionOptions?.filter((item) => item.value == formState.opinionId)[0]?.label ==
                    '不属于我单位管辖，建议移送处理。'
                "
              >
                <a-input
                  v-model:value="formState.sendName"
                  :placeholder="
                    caseSenNamePlaceholder(
                      opinionOptions?.filter((item) => item.value == formState.opinionId)[0]?.label,
                    )
                  "
                ></a-input>
              </a-form-item> </a-col
          ></a-row>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="8">
              <a-form-item
                label="执法机构"
                name="agencyId"
                :labelCol="{ style: { width: '82px' } }"
              >
                <a-select
                  v-model:value="formState.agencyId"
                  placeholder="请选择执法机构"
                  :options="agencyOptions"
                  allowClear
                  @change="agencyChange"
                >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="审批负责人" name="approveId">
                <a-select
                  v-model:value="formState.approveId"
                  placeholder="请选择审批负责人"
                  :options="approveOptions"
                  allowClear
                >
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>
    <div class="bottomBox"></div>
    <div class="bottomBtns" style="z-index: 3">
      <a-space :size="12">
        <a-button @click="cacel" size="large">取消</a-button>
        <a-button type="primary" @click="onSubmit(1)" size="large">保存</a-button>
        <a-button type="primary" @click="onSubmit(0)" size="large">提交审批</a-button>
      </a-space>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, toRaw, onMounted } from 'vue';
  import {
    isPhoneNumberValid,
    isChinaIDCard,
    getKeys,
    isHKCard,
    isPassPortCard,
  } from '@/utils/common';
  import type { Rule } from 'ant-design-vue/es/form';
  import { message } from 'ant-design-vue';
  import router from '@/router';
  import { useRoute } from 'vue-router';
  import { getDeptList, getInfo, getUserList, organizerList } from '@/api/account';
  import {
    caseDetail,
    editCaseInfo,
    getAreaList,
    getCaseActionPageList,
    getCaseOption,
    getFromType,
    insertCaseInfo,
  } from '@/api/supervision/case-management';
  import { getIdType } from '@/api/supervision/create-task';
  import { useTable } from '@/components/core/dynamic-table';
  import { taskxfInfo } from '@/api/supervision/task-management';
  import { getPlaceInfo, getSiteNameList } from '@/api/site';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  const tabsViewStore = useTabsViewStore();

  const [DynamicTable, dynamicTableInstance] = useTable();

  const route = useRoute();

  const formRef = ref();
  const labelCol = {
    style: { width: '109px' },
  };
  const formState = reactive({
    sourceId: undefined, //案件来源id
    sourceName: '', //案件来源名称
    otherSource: '', //其他来源，来源类型选择“其他”时有值
    caseActionId: '', //案由id
    caseActionName: '', //案由名称
    caseBrief: '', //简要案情
    enforceWay: undefined, //执法方式；1.委托执法；2.授权执法；
    taskId: '', //任务id，从任务处立案时有值
    opinionId: undefined, //立案意见id
    opinion: '', //立案意见
    sendName: '', //移送单位的名称/其他立案意见
    agencyId: undefined, //执法机构id
    agencyName: '', //执法机构名称
    draftFlag: undefined, //是否为草稿；0.否；1.是
    approveId: undefined, //审核人id
    approveName: '', //审核人姓名

    // organizerId: undefined, //协作人
    // organizerName: '',
    partyType: 0, //当事人类型
    placeName: '', //单位(场所)名称/姓名/字号名称
    placeId: '',
    sex: undefined, //性别
    birthDate: '', //出生日期
    contactsTel: '', //自然人/单位联系电话
    idType: undefined, //证件类型
    idCode: '', //证件号码
    operateArea: [], //住址
    operateAddress: '', //详细地址
    registerArea: [], //注册地址
    registerAddress: '', //详细注册地址
    headName: '', //法人
    headTel: '', //法人电话
  });

  const boxTittle = ref('立案');

  const open = ref<boolean>(false);

  const draftFlag = ref(1);

  const showModal = () => {
    open.value = true;
  };

  const handleOk = (e: MouseEvent) => {
    if (selectedRowName.value != '') {
      open.value = false;
      formRef.value.clearValidate('caseActionId');
      formState.caseActionId = selectedRowKeys.value[0];
      formState.caseActionName = selectedRowName.value;
    } else {
      message.error('请选择案由！');
    }
  };

  const columns = [
    {
      title: '案由',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '案由',
      dataIndex: 'keyword',
      hideInTable: true,
      formItemProps: {
        labelWidth: 45,
        componentProps: () => {
          return {
            placeholder: '请输入案由搜索',
            autocomplete: 'off',
            disabledLabelWidth: true,
          };
        },
      },
    },
  ];

  const selectedRowKeys = ref([]);
  const selectedRowName = ref('');

  const onRowChange = (a, e) => {
    selectedRowKeys.value = a;
    selectedRowName.value = e[0].name;
  };

  const loadData = async (params): Promise<API.TableListResult> => {
    const data = await getCaseActionPageList(params);
    console.log(data);

    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list: data,
          ...params,
        });
      }, 500);
    });
  };

  const validateSourceId = async (_rule: Rule, value: string) => {
    if (value === undefined) {
      let message = '请选择案件来源';
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };

  const validateCaseActionId = async (_rule: Rule, value: string) => {
    if (value === '') {
      let message = '请选择案由';
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };

  const validateOpinionId = async (_rule: Rule, value: string) => {
    if (value === undefined) {
      let message = '请选择立案意见';
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };

  const validatePlaceName = async (_rule: Rule, value: string) => {
    if (value === '') {
      let message = ['请输入姓名', '请选择单位名称', '请输入字号名称', '请选择单位名称'][
        formState.partyType
      ];
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };

  const validateOperateArea = async (_rule: Rule, value: string) => {
    if (value == '') {
      let message = ['请选择住址', '请选择经营地址', '请选择经营地址', '请选择经营地址'][
        formState.partyType
      ];
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };

  const validateContactsTel = async (_rule: Rule, value: string) => {
    if (value === '') {
      let message = [
        '请输入联系电话',
        '请输入单位联系电话',
        '请输入单位联系电话',
        '请输入单位联系电话',
      ][formState.partyType];
      return Promise.reject(message);
    } else {
      if (isPhoneNumberValid(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject('请填写正确的手机号码');
      }
    }
  };

  const validateContactsTels = async (_rule: Rule, value: string) => {
    if (value === '') {
      let message = [
        '请输入联系电话',
        '请输入单位联系电话',
        '请输入单位联系电话',
        '请输入单位联系电话',
      ][formState.partyType];
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };

  const validateContactsTelss = async (_rule: Rule, value: string) => {
    if (value === '') {
      let message = ['', '请输入法人电话', '', '请输入负责人电话'][formState.partyType];
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };

  const validateIdCode = async (_rule: Rule, value: string) => {
    if (value === '') {
      let message = [
        '请输入证件号码',
        '请输入社会统一信用代码',
        '请输入社会统一信用代码',
        '请输入社会统一信用代码',
      ][formState.partyType];
      return Promise.reject(message);
    } else if (formState.idType == '身份证') {
      if (isChinaIDCard(value) || formState.partyType !== 0) {
        return Promise.resolve();
      } else {
        let message = [
          '请输入正确的证件号码',
          '请输入正确的社会统一信用代码',
          '请输入正确的社会统一信用代码',
          '请输入正确的社会统一信用代码',
        ][formState.partyType];
        return Promise.reject(message);
      }
    } else if (formState.idType == '港澳通行证') {
      if (isHKCard(value) || formState.partyType !== 0) {
        return Promise.resolve();
      } else {
        return Promise.reject('港澳居民来往内地通行证号码不合规');
      }
    } else if (formState.idType == '护照') {
      if (isPassPortCard(value) || formState.partyType !== 0) {
        return Promise.resolve();
      } else {
        return Promise.reject('护照号码不合规');
      }
    }
  };

  const validateHeadName = async (_rule: Rule, value: string) => {
    if (value === '') {
      let message = ['', '请输入法人姓名', '请输入经营者姓名', '请输入负责人姓名'][
        formState.partyType
      ];
      return Promise.reject(message);
    } else {
      return Promise.resolve();
    }
  };
  const rules = {
    sourceId: [
      {
        required: true,
        validator: validateSourceId,
        trigger: 'change',
      },
    ],
    otherSource: [
      {
        required: true,
        message: '请填写其他来源',
        trigger: 'change',
      },
    ],
    caseActionId: [
      {
        required: true,
        validator: validateCaseActionId,
        trigger: 'change',
      },
    ],
    caseBrief: [
      {
        required: true,
        message: '请输入简要案情',
        trigger: 'change',
      },
    ],
    enforceWay: [
      {
        required: true,
        message: '请选择执法方式',
        trigger: 'change',
      },
    ],
    opinionId: [
      {
        required: true,
        validator: validateOpinionId,
        trigger: 'change',
      },
    ],
    sendName: [
      {
        required: true,
        message: '请输入移送单位名称或者其他意见',
        trigger: 'change',
      },
    ],
    agencyId: [
      {
        required: true,
        message: '请选择执法机构',
        trigger: 'change',
      },
    ],
    approveId: [
      {
        required: true,
        message: '请选择审核人',
        trigger: 'change',
      },
    ],
    partyType: [
      {
        required: true,
        message: '请选择当事人类型',
        trigger: 'change',
      },
    ],
    placeName: [
      {
        required: true,
        validator: validatePlaceName,
        // message: ['请输入姓名', '请输入单位名称'][formState.partyType],
        trigger: 'change',
      },
    ],
    sex: [
      {
        required: true,
        message: '请选择性别',
        trigger: 'change',
      },
    ],
    birthDate: [
      {
        required: true,
        message: '请选择出生日期',
        trigger: 'change',
      },
    ],
    contactsTel: [
      {
        required: true,
        validator: validateContactsTels,
        trigger: 'blur',
      },
    ],
    idType: [
      {
        required: true,
        message: '请选择证件类型',
        trigger: 'change',
      },
    ],
    idCode: [
      {
        required: true,
        validator: validateIdCode,
        trigger: 'blur',
      },
    ],
    operateArea: [
      {
        required: true,
        validator: validateOperateArea,
        trigger: 'change',
      },
    ],
    operateAddress: [
      {
        required: true,
        message: '请输入详细地址',
        trigger: 'change',
      },
    ],
    registerArea: [
      {
        required: true,
        message: '请选择注册地址',
        trigger: 'change',
      },
    ],
    registerAddress: [
      {
        required: true,
        message: '请输入详细地址',
        trigger: 'change',
      },
    ],
    headName: [
      {
        required: true,
        validator: validateHeadName,
        trigger: 'blur',
      },
    ],
    headTel: [
      {
        required: true,
        validator: validateContactsTelss,
        trigger: 'blur',
      },
    ],
  } as any;

  const cacel = () => {
    router.push({
      path: '/administrative-penalty/administrative-penalty/case-management',
    });
  };
  const onSubmit = (val) => {
    formRef.value
      .validate()
      .then(async () => {
        let idTypeName = '';
        let operateCountyCode = '';
        let operateCounty = '';
        let operateTownCode = '';
        let operateTown = '';
        let registerCountyCode = '';
        let registerCounty = '';
        let registerTownCode = '';
        let registerTown = '';
        let sourceName = '';
        let opinion = '';
        let agencyName = '';
        let approveName = '';
        if (formState.operateArea) {
          operateCountyCode = formState.operateArea[0];
          operateCounty = getKeys(addressOptions.value, formState.operateArea[0], 'name') as any;
          operateTownCode = formState.operateArea[1];
          operateTown = getKeys(addressOptions.value, formState.operateArea[1], 'name') as any;
        }
        if (formState.registerArea) {
          registerCountyCode = formState.registerArea[0];
          registerCounty = getKeys(registerAddress.value, formState.registerArea[0], 'name') as any;
          registerTownCode = formState.registerArea[1];
          registerTown = getKeys(registerAddress.value, formState.registerArea[1], 'name') as any;
        }
        if (formState.idType) {
          idTypeName = idTypeOptions.value.find((item) => item.value == formState.idType).label;
        }
        if (formState.sourceId) {
          sourceName = sourceTypeOptions.value.find(
            (item) => item.value == formState.sourceId,
          ).label;
        }
        if (formState.opinionId) {
          opinion = opinionOptions.value.find((item) => item.value == formState.opinionId).label;
        }
        if (formState.agencyId) {
          agencyName = agencyOptions.value.find((item) => item.value == formState.agencyId).label;
        }
        if (formState.approveId) {
          approveName = approveOptions.value.find(
            (item) => item.value == formState.approveId,
          ).label;
        }

        let params = {
          id: route.query.id || '',
          // organizerId: formState.organizerId || '',
          // organizerName: organizerOptions?.value.find((item) => item.value == formState.organizerId)
          //   .label,
          sourceId: formState.sourceId,
          sourceName,
          otherSource: formState.otherSource || '',
          caseActionId: formState.caseActionId || '',
          caseActionName: formState.caseActionName || '',
          caseBrief: formState.caseBrief || '',
          taskId: route.query.caseId || '',
          opinionId: formState.opinionId || '',
          opinion,
          sendName: formState.sendName || '',
          agencyId: formState.agencyId || '',
          agencyName,
          draftFlag: val,
          approveId: formState.approveId || '',
          approveName,
          enforceWay: formState.enforceWay || '',
          placeInfo: {
            partyType: formState.partyType,
            placeName: formState.placeName || '',
            sex: formState.sex || '',
            birthDate: formState.birthDate || '',
            contactsTel: formState.contactsTel || '',
            idType: formState.idType || '',
            idTypeName,
            idCode: formState.idCode || '',
            operateCountyCode,
            operateCounty,
            operateTownCode,
            operateTown,
            registerCountyCode,
            registerCounty,
            registerTownCode,
            registerTown,
            headName: formState.headName || '',
            headTel: formState.headTel || '',
            operateAddress: formState.operateAddress || '',
            registerAddress: formState.registerAddress || '',
          },
        };

        console.log(params);

        if (route.query.caseId) {
          params.taskId = route.query.caseId;
        }

        if (route.query.id) {
          const res = await editCaseInfo(params);
          if (res.code == 0) {
            message.success('编辑立案成功！');
            tabsViewStore.closeCurrentTabToUrl(
              route,
              '/administrative-penalty/administrative-penalty/case-management',
            );
          }
        } else {
          const res = await insertCaseInfo(params);
          if (res.code == 0) {
            message.success('添加立案成功！');
            tabsViewStore.closeCurrentTabToUrl(
              route,
              '/administrative-penalty/administrative-penalty/case-management',
            );
          }
        }
      })
      .catch((error) => {
        console.log('error', error);
      });
  };

  const changeParty = () => {
    formState.placeName = '';
    formState.sex = undefined;
    formState.birthDate = '';
    formState.contactsTel = '';
    formState.idType = undefined;
    formState.idCode = '';
    formState.operateArea = [];
    formState.operateAddress = '';
    formState.registerArea = [];
    formState.registerAddress = '';
    formState.headName = '';
    formState.headTel = '';
  };

  const caseIdcode = (val) => {
    let idTypeName = '';
    if (idTypeOptions.value) {
      idTypeName = idTypeOptions.value.find((item) => item.value == val)?.label;
    }

    switch (idTypeName) {
      case '身份证':
        return 18;
      case '护照':
        return 9;
      case '港澳通行证':
        return 9;
      default:
        return 18;
    }
  };

  const caseSenNameLabel = (val) => {
    switch (val) {
      case '其他':
        return '其他';
      case '不属于我单位管辖，建议移送处理。':
        return '移送单位';
      default:
        return '';
    }
  };

  const caseSenNamePlaceholder = (val) => {
    switch (val) {
      case '其他':
        return '请输入其他意见';
      case '不属于我单位管辖，建议移送处理。':
        return '请输入移送单位名称';
      default:
        return '';
    }
  };

  const placeId = ref('');

  interface MockVal {
    label: string;
    value: string;
  }
  const placeOptions = ref<MockVal[]>([]);

  const onSelect = async (value: string) => {
    formState.placeId = value;
    formState.placeName = placeOptions.value.find((item) => item.value == value)?.label as any;

    if (formState.placeName && formState.placeId) {
      const data = await getPlaceInfo(formState.placeId);
      formState.placeId = data.id;
      formState.placeName = data.placeName;
      formState.sex = data.sex;
      formState.birthDate = data.birthDate;
      formState.contactsTel = data.contactsTel;
      formState.idType = data.idType;
      formState.idCode = data.idCode;
      formState.operateAddress = data.operateAddress;
      formState.registerAddress = data.registerAddress;
      formState.headName = data.headName;
      formState.headTel = data.headTel;
      formState.operateArea = [data.operateCountyCode, data.operateTownCode] as any;
      formState.registerArea = [data.registerCountyCode, data.registerTownCode] as any;
    }
  };

  const changeInfo = async () => {
    const res = await getSiteNameList({ placeName: formState.placeName });
    placeOptions.value = res.map((item) => {
      return {
        label: item.placeName,
        value: item.id,
      };
    });
  };

  //性别
  const sexOptions = [
    {
      label: '男',
      value: 1,
    },
    {
      label: '女',
      value: 2,
    },
  ];

  const userName = ref();

  //检查类型相关
  const sourceTypeOptions = ref();

  //立案意见
  const opinionOptions = ref();

  //执法机构
  const agencyOptions = ref();

  const agencyChange = async (e) => {
    if (e) {
      const userList = await getUserList(e, 2);
      approveOptions.value = userList.map((item) => {
        return {
          label: item.userName,
          value: item.id,
        };
      });
    }
  };

  //执法方式
  const enforceWayOptions = ref([
    {
      value: 1,
      label: '委托执法',
    },
    {
      value: 2,
      label: '授权执法',
    },
  ]);

  //审批负责人
  const approveOptions = ref();

  //协作人
  const organizerOptions = ref();

  //证件类型
  const idTypeOptions = ref();

  const caseData = ref();

  //区域相关
  const addressOptions = ref();
  const registerAddress = ref();
  const areaFieldNames = {
    label: 'name',
    value: 'id',
  };

  const taskData = ref();

  onMounted(async () => {
    const userData = await getInfo();
    userName.value = userData.userName;

    const from_type = await getFromType();
    if (from_type.code === 0) {
      sourceTypeOptions.value = from_type.data.map((item) => {
        return {
          label: item.configName,
          value: item.id,
        };
      });
      console.log(sourceTypeOptions.value[0].label);
    }
    const res_id = await getIdType();
    if (res_id.code === 0) {
      idTypeOptions.value = res_id.data.map((item) => {
        return {
          label: item.configName,
          value: item.id,
        };
      });
    }
    const res_area = await getAreaList();
    if (res_area.code === 0) {
      addressOptions.value = res_area.data[0].children;
      registerAddress.value = res_area.data[0].children;
    }

    const case_option = await getCaseOption();
    if (case_option.code === 0) {
      opinionOptions.value = case_option.data.map((item) => {
        return {
          label: item.configName,
          value: item.id,
        };
      });
    }

    const dept_option = await getDeptList();

    agencyOptions.value = dept_option.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });

    if (route.query.id) {
      boxTittle.value = '编辑';
      caseData.value = await caseDetail(route.query.id);
      formState.sourceId = caseData.value.sourceId;
      formState.sourceName = caseData.value.sourceName;
      formState.otherSource = caseData.value.otherSource;
      formState.caseActionId = caseData.value.caseActionId;
      formState.caseActionName = caseData.value.caseActionName;
      formState.enforceWay = caseData.value.enforceWay;

      formState.caseBrief = caseData.value.caseBrief;
      formState.taskId = caseData.value.taskId;
      formState.opinionId = caseData.value.opinionId;
      formState.opinion = caseData.value.opinion;
      formState.sendName = caseData.value.sendName;
      formState.agencyId = caseData.value.agencyId;
      formState.agencyName = caseData.value.agencyName;
      formState.approveId = caseData.value.approveId;
      formState.approveName = caseData.value.approveName;
      const userList = await getUserList(caseData.value.agencyId, 2);
      approveOptions.value = userList.map((item) => {
        return {
          label: item.userName,
          value: item.id,
        };
      });

      formState.partyType = caseData.value.placeInfo.partyType;
      formState.placeName = caseData.value.placeInfo.placeName;
      formState.sex = caseData.value.placeInfo.sex;
      formState.birthDate = caseData.value.placeInfo.birthDate;
      formState.contactsTel = caseData.value.placeInfo.contactsTel;
      formState.idType = caseData.value.placeInfo.idType;
      formState.idCode = caseData.value.placeInfo.idCode;
      formState.operateAddress = caseData.value.placeInfo.operateAddress;
      formState.registerAddress = caseData.value.placeInfo.registerAddress;
      formState.headName = caseData.value.placeInfo.headName;
      formState.headTel = caseData.value.placeInfo.headTel;
      formState.operateArea = [
        caseData.value.placeInfo.operateCountyCode,
        caseData.value.placeInfo.operateTownCode,
      ] as any;
      formState.registerArea = [
        caseData.value.placeInfo.registerCountyCode,
        caseData.value.placeInfo.registerTownCode,
      ] as any;
    }
    if (route.query.caseId) {
      const data = await taskxfInfo(route.query.caseId);
      taskData.value = data;
      formState.partyType = taskData.value.placeInfo.partyType;
      formState.placeName = taskData.value.placeInfo.placeName;
      formState.sex = taskData.value.placeInfo.sex;
      formState.birthDate = taskData.value.placeInfo.birthDate;
      formState.contactsTel = taskData.value.placeInfo.contactsTel;
      formState.idType = taskData.value.placeInfo.idType;
      formState.idCode = taskData.value.placeInfo.idCode;
      formState.operateAddress = taskData.value.placeInfo.operateAddress;
      formState.registerAddress = taskData.value.placeInfo.registerAddress;
      formState.headName = taskData.value.placeInfo.headName;
      formState.headTel = taskData.value.placeInfo.headTel;
      formState.operateArea = [
        taskData.value.placeInfo.operateCountyCode,
        taskData.value.placeInfo.operateTownCode,
      ] as any;
      formState.registerArea = [
        taskData.value.placeInfo.registerCountyCode,
        taskData.value.placeInfo.registerTownCode,
      ] as any;
    }
  });
</script>

<style lang="less" scoped>
  .register-box {
    background-color: #fff;

    &-top {
      &-tittle {
        padding: 0 0 16px;
        border-bottom: 1px solid rgb(240 240 240 / 100%);
        color: rgb(68 68 68 / 100%);
        font-size: 18px;
        font-weight: 700;
        line-height: 26px;
      }
    }

    .base-info {
      .baseBox {
        width: 68%;
        margin: 0 0 16px 95px;
        border: 1px solid #f0f0f0;

        &-body {
          padding: 16px 16px 0 0;
        }
      }

      .partyType {
        .ant-radio-button-wrapper {
          border-color: #f0f0f0;
          border-bottom: 0;
        }

        .ant-radio-button-wrapper:first-child {
          border-inline-start: 1px solid #f0f0f0;
        }
        .ant-radio-button-wrapper:not(:first-child)::before {
          background-color: #f0f0f0;
        }
      }
    }

    .registerBox {
      &-tittle {
        display: flex;
        align-items: center;
        padding: 13px 0;

        &-left {
          height: 14px;
          margin-right: 7px;
          border: 1px solid #0f53ac;
          border-radius: 4px;
        }

        &-right {
          color: rgb(68 68 68 / 100%);
          font-size: 16px;
          font-weight: 400;
          line-height: 24px;
        }
      }
    }

    .casePadding {
      padding: 0 0 13px 0;
    }

    :global(.ant-form-item.partyType) {
      margin-bottom: 0 !important;
    }

    //lable字数大于5时，红点对齐第一行文字
    :global(.itemForm.ant-form-item .ant-form-item-label > label) {
      align-items: baseline;
      line-height: 15px;
    }

    .bottomBox {
      height: 60px;
    }

    .bottomBtns {
      position: fixed;
      bottom: 0;
      width: calc(100% - 200px);
      padding: 8px 20px;
      border-top: 1px solid rgb(240 240 240 / 100%);
      background: rgb(255 255 255 / 100%);
      text-align: right;
    }
  }
</style>
